<template>
  <div class="login">
    <div class="left-wrap">
      <left-view></left-view>
    </div>
    <div class="right-wrap">
      <div class="top-right-wrap">
        <div class="btn theme-btn" @click="toggleTheme">
          <i class="iconfont-sys">
            {{ isDark ? '&#xe6b5;' : '&#xe725;' }}
          </i>
        </div>
      </div>
      <div class="header">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#iconsys-zhaopian-copy"></use>
        </svg>
        <h1>{{ systemName }}</h1>
      </div>
      <div class="login-wrap">
        <div class="form">
          <h3 class="title">欢迎回来</h3>
          <p class="sub-title">输入您的账号和密码登录</p>
          <el-form ref="formRef" :model="formData" :rules="rules" @keyup.enter="handleSubmit" style="margin-top: 25px">
            <el-form-item prop="username">
              <el-input placeholder="请输入账号" size="large" v-model.trim="formData.username" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input placeholder="请输入密码" size="large" v-model.trim="formData.password" type="password" radius="8px"
                autocomplete="off" />
            </el-form-item>
            <el-form-item label="">
              <el-input size="large" placeholder="请输入验证码" clearable prefix-icon="el-icon-unlock" v-model="user.captcha"
                style="width:230px;margin-right: 40px;"></el-input>
              <img :src="codeUrl" @click="reload" style="cursor: pointer;float:right;" />
            </el-form-item>
            <div class="forget-password">
              <el-checkbox v-model="formData.rememberPassword">记住密码</el-checkbox>
            </div>

            <div style="margin-top: 30px">
              <el-button class="login-btn" size="large" type="primary" @click="handleSubmit" :loading="loading">
                登录
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import LeftView from '@/components/Pages/Login/LeftView.vue'
import { SystemInfo } from '@/config/setting'
import { ElMessage, ElNotification } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { HOME_PAGE } from '@/router/modules/routesAlias'
import { ApiStatus } from '@/utils/http/status'
import { SystemThemeEnum } from '@/enums/appEnum'
import { useSettingStore } from '@/store/modules/setting'
import type { FormInstance, FormRules } from 'element-plus'

const userStore = useUserStore()
const router = useRouter()

const codeUrl = ref('api/admin/common/captcha?rand='+new Date().getTime())
const user = reactive({
  captcha:''
})
const systemName = SystemInfo.name
const formRef = ref<FormInstance>()
const formData = reactive({
  username: SystemInfo.login.username,
  password: SystemInfo.login.password,
  rememberPassword: true
})

const rules = computed<FormRules>(() => ({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}))

const loading = ref(false)

const store = useSettingStore()
const isDark = computed(() => store.isDark)

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true

      // 延时辅助函数
      const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

      try {
        const res = await UserService.login({
            username: formData.username,
            password: formData.password,
            captcha: user.captcha
        })

        console.log(res,'登录返回')
        if (res.code === ApiStatus.success) {
          // 设置 token
          userStore.setToken(res.data.token)

          // 获取用户信息
          const userRes = await UserService.getUserInfo()
          if (userRes.code === ApiStatus.success) {
            userStore.setUserInfo(userRes.data)
          }

          // 设置登录状态
          userStore.setLoginStatus(true)
          // 延时辅助函数
          await delay(1000)
          // 登录成功提示
          showLoginSuccessNotice()
          // 跳转首页
          router.push(HOME_PAGE)
        } else {
          ElMessage.error(res.message)
        }
      } finally {
        await delay(1000)
        loading.value = false
      }
    }
  })
}
// // 再次获取验证码
const reload = () =>{
  codeUrl.value = 'api/admin/common/captcha?rand='+new Date().getTime()
}
// 登录成功提示
const showLoginSuccessNotice = () => {
  setTimeout(() => {
    ElNotification({
      title: '登录成功',
      type: 'success',
      showClose: true,
      duration: 2500,
      zIndex: 10000,
      message: `欢迎回来, ${systemName}!`
    })
  }, 300)
}

// 切换主题
import { useTheme } from '@/composables/useTheme'
import { UserService } from '@/api/usersApi'

const toggleTheme = () => {
  let { LIGHT, DARK } = SystemThemeEnum
  useTheme().switchTheme(useSettingStore().systemThemeType === LIGHT ? DARK : LIGHT)
}
</script>

<style lang="scss" scoped>
@use './index';
</style>
